<script setup lang="ts">
import { ref, onMounted, watch, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRouter, useRoute } from 'vue-router'
// @ts-ignore
import { ReadClients, WriteClients } from '@/Urls/AxiosHelper'

const router = useRouter()
const route = useRoute()

// 从路由参数获取ID
const props = defineProps<{ id?:number | string }>()
const id = computed(() => props.id || route.query.id)

const readClient = ReadClients[3]
const writeClient = WriteClients[3]
const loading = ref(false)
const data = ref<any>({
  creator: '李小海',
  createTime: '2025-09-19 16:11:56',
  updater: '李小海',
  updateTime: '2025-09-19 16:11:56',
})

// 工序组成数据
const processList = ref<any[]>([])
// 关联产品数据
const relatedProducts = ref<any[]>([])
// 当前激活的标签页
const activeTab = ref('info')

async function handleDelete(){
  try{
    await ElMessageBox.confirm(`确认删除【${data.value?.processRouteName || ''}】吗？`, '提示', { type:'warning' })
    await writeClient.get('/api/ProcessRoute/DeleteProcessRoute', { params:{ Id: props.id } })
    ElMessage.success('删除成功')
    router.push({ name: 'ProcessRouteInfo' })
  }catch(err:any){
    // 区分用户取消和实际错误
    if (err === 'cancel' || err?.message === 'cancel') {
      ElMessage.info('已取消删除')
    } else {
      console.error('删除失败:', err)
      ElMessage.error('删除失败')
    }
  }
}

function handleEdit(){
  router.push({ name: 'ProcessRouteEdit', query: { id: id.value, origin: 'detail' } })
}

async function handleExport(){
  try{
    const url = `${readClient.defaults.baseURL}/api/ProcessRoute/Export`
    window.location.href = url
    ElMessage.success('导出任务已发起')
  }catch{ ElMessage.error('导出失败') }
}

// 获取工序组成列表
async function fetchProcessList(){
  if(!data.value?.processRouteNumber) return
  try{
    console.log('获取工序列表，processRouteNumber:', data.value.processRouteNumber)
    const res = await readClient.get('/productread/api/Process/GetProcessById', { params: { processRouteNumber: data.value.processRouteNumber } })
    console.log('工序列表响应:', res)
    const responseData = res?.data?.data || res?.data || res
    if(Array.isArray(responseData)){
      processList.value = responseData.map((item: any) => ({
        serialNumber: item.serialNumber || '',
        processNumber: item.processNumber || '',
        processName: item.processName || '',
        nextProcess: item.nextProcess || '',
        relationship: item.relationship || '',
        isCriticalProcess: item.isCriticalProcess || false,
        preparationTime: item.preparationTime || 0,
        waitingTime: item.waitingTime || 0,
        color: item.color || '#409EFF'
      }))
      console.log('工序列表处理结果:', processList.value)
    }
  }catch(err){
    console.error('获取工序列表失败:', err)
  }
}

// 获取关联产品列表
async function fetchRelatedProducts(){
  if(!data.value?.processRouteNumber) return
  try{
    console.log('获取关联产品列表，processRouteNumber:', data.value.processRouteNumber)
    const res = await readClient.get('/productread/api/ProductProcess/ProductProcessShow', { params: { processRouteNumber: data.value.processRouteNumber } })
    console.log('关联产品列表响应:', res)
    const responseData = res?.data?.data || res?.data || res
    if(Array.isArray(responseData)){
      relatedProducts.value = responseData.map((item: any, index: number) => ({
        serialNumber: index + 1,
        productNumber: item.productNumber || '',
        productName: item.productName || '',
        specificationModel: item.specificationModel || '',
        unit: item.unit || '',
        bomNumber: item.bomNumber || '',
        bomVersion: item.bomVersion || ''
      }))
      console.log('关联产品列表处理结果:', relatedProducts.value)
    }
  }catch(err){
    console.error('获取关联产品列表失败:', err)
  }
}

async function fetchDetail(){
  if(!id.value) return
  loading.value = true
  try{
    console.log('获取工艺路线详情，ID:', id.value)
    const res = await readClient.get('/productread/api/ProcessRoute/GetProcessRouteById', { params:{ Id: id.value } })
    console.log('工艺路线详情响应:', res)
    const payload = res?.data
    data.value = payload?.data || payload || null
    console.log('工艺路线详情数据:', data.value)
    
    // 获取工序组成和关联产品
    if(data.value?.processRouteNumber){
      await fetchProcessList()
      await fetchRelatedProducts()
    }
  }catch(err){
    console.error('获取详情失败:', err)
    ElMessage.error('获取详情失败')
  }
  finally{ loading.value = false }
}

onMounted(fetchDetail)
watch(()=>id.value, fetchDetail)
</script>

<template>
  <div class="detail-wrap" v-loading="loading">
    <el-card class="top-card">
      <div class="card-header">
        <div class="title">{{ data?.processRouteName || '工艺路线详情' }} <span class="code">{{ data?.processRouteNumber }}</span></div>
        <div class="meta">
          <span>创建人：{{ data?.creator || '-' }}</span>
          <span>创建时间：{{ data?.createTime || '-' }}</span>
          <span>更新人：{{ data?.updater || '-' }}</span>
          <span>更新时间：{{ data?.updateTime || '-' }}</span>
        </div>
        <div class="spacer"></div>
      </div>
      <div class="btn-bar">
        <el-button size="large" plain @click="handleEdit">编辑</el-button>
        <el-button size="large" plain @click="handleDelete">删除</el-button>
        <el-button size="large" plain @click="handleExport">导出</el-button>
      </div>
    </el-card>

    <el-card class="content-card">
      <el-tabs v-model="activeTab" class="detail-tabs">
        <el-tab-pane label="基础信息" name="info">
          <div class="section">
            <el-descriptions :column="2" border size="large">
              <el-descriptions-item label="工艺路线编号">{{ data?.processRouteNumber || '-' }}</el-descriptions-item>
              <el-descriptions-item label="工艺路线名称">{{ data?.processRouteName || '-' }}</el-descriptions-item>
              <el-descriptions-item label="状态">{{ (data?.status===true||data?.status===1||data?.status==='true')?'启用':'禁用' }}</el-descriptions-item>
              <el-descriptions-item label="说明" :span="2">{{ data?.description || '-' }}</el-descriptions-item>
              <el-descriptions-item label="备注" :span="2">{{ data?.remarks || '-' }}</el-descriptions-item>
            </el-descriptions>
          </div>
        </el-tab-pane>
        <el-tab-pane label="工序组成" name="process">
          <div class="op-row">
            <el-button type="primary" size="large">导出</el-button>
          </div>
          <el-table :data="processList" height="400">
            <el-table-column type="selection" width="55" />
            <el-table-column label="序号" width="80" align="center">
              <template #default="scope">{{ scope.row.serialNumber }}</template>
            </el-table-column>
            <el-table-column prop="processNumber" label="工序编号" min-width="140" />
            <el-table-column prop="processName" label="工序名称" min-width="140" />
            <el-table-column prop="nextProcess" label="下一道工序" min-width="140" />
            <el-table-column prop="relationship" label="与下一道工序关系" min-width="160" />
            <el-table-column label="关键工序" width="100" align="center">
              <template #default="scope">
                <el-tag :type="scope.row.isCriticalProcess ? 'danger' : 'info'">{{ scope.row.isCriticalProcess ? '是' : '否' }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="preparationTime" label="准备时间" width="120" align="center" />
            <el-table-column prop="waitingTime" label="等待时间" width="120" align="center" />
            <el-table-column label="颜色" width="80" align="center">
              <template #default="scope">
                <div class="color-swatch" :style="{ backgroundColor: scope.row.color }"></div>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        
        <el-tab-pane label="关联产品" name="products">
          <div class="op-row">
            <el-button type="primary" size="large">导出</el-button>
          </div>
          <el-table :data="relatedProducts" height="400">
            <el-table-column type="selection" width="55" />
            <el-table-column label="序号" width="80" align="center">
              <template #default="scope">{{ scope.row.serialNumber }}</template>
            </el-table-column>
            <el-table-column prop="productNumber" label="产品编号" min-width="140">
              <template #default="scope">
                <el-link type="primary" underline="never">{{ scope.row.productNumber }}</el-link>
              </template>
            </el-table-column>
            <el-table-column prop="productName" label="产品名称" min-width="140" />
            <el-table-column prop="specificationModel" label="规格型号" min-width="140" />
            <el-table-column prop="unit" label="单位" width="80" align="center" />
            <el-table-column prop="bomNumber" label="BOM编号" min-width="140" />
            <el-table-column prop="bomVersion" label="BOM版本" width="120" align="center" />
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <el-card class="section-card">
      <div class="op-bottom">
        <el-button size="large" type="primary" @click="router.push({ name: 'ProcessRouteInfo' })">返回列表</el-button>
      </div>
    </el-card>
  </div>
</template>

<style scoped>
/* 整体布局 */
.detail-wrap{ 
  display:flex; 
  flex-direction:column; 
  gap:20px; 
  padding:20px;
  background: #f5f7fa;
  min-height: 100vh;
}

/* 顶部卡片样式 */
.top-card {
  background: white;
  border: 1px solid #ebeef5;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0,0,0,0.1);
}

.top-card :deep(.el-card__body) {
  padding: 24px;
}

.card-header{ 
  display:flex; 
  flex-direction:column; 
  align-items:flex-start; 
  gap:12px; 
  margin-bottom: 20px;
}

.card-header .title{ 
  font-size:24px; 
  font-weight:600; 
  line-height:1.4; 
  color: #303133;
  margin: 0;
}

.card-header .title .code{ 
  font-size:16px; 
  font-weight:400; 
  color:#909399; 
  margin-left:12px; 
  background: #f5f7fa;
  padding: 4px 12px;
  border-radius: 4px;
}

.card-header .meta{ 
  display:flex; 
  gap:32px; 
  color:#606266; 
  font-size:14px; 
  flex-wrap: wrap;
}

.card-header .meta span {
  background: #f5f7fa;
  padding: 6px 12px;
  border-radius: 4px;
  font-weight: 500;
}

.btn-bar{ 
  display:flex; 
  gap:12px; 
  padding-top:16px; 
  flex-wrap: wrap;
}

.btn-bar .el-button {
  font-weight: 500;
  padding: 10px 20px;
  border-radius: 6px;
}

/* 内容卡片样式 */
.content-card {
  background: white;
  border: 1px solid #ebeef5;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0,0,0,0.1);
}

.content-card :deep(.el-card__body) {
  padding: 0;
}

/* 标签页样式 */
.detail-tabs :deep(.el-tabs__header) {
  margin: 0;
  background: #f5f7fa;
  padding: 0 20px;
  border-bottom: 1px solid #ebeef5;
}

.detail-tabs :deep(.el-tabs__item) {
  font-size: 15px;
  font-weight: 500;
  color: #606266;
  padding: 16px 24px;
  border: none;
}

.detail-tabs :deep(.el-tabs__item.is-active) {
  color: #409eff;
  background: white;
  border-radius: 6px 6px 0 0;
}

.detail-tabs :deep(.el-tabs__item:hover) {
  color: #409eff;
}

.detail-tabs :deep(.el-tabs__content) {
  padding: 24px;
}

/* 基础信息样式 */
.section{ 
  border: 1px solid #ebeef5;
  border-radius: 8px; 
  padding: 24px; 
  margin-top: 0;
  background: white;
}

.section :deep(.el-descriptions__header) {
  margin-bottom: 20px;
}

.section :deep(.el-descriptions__title) {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.section :deep(.el-descriptions__body) {
  background: #fafafa;
  border-radius: 6px;
  border: 1px solid #ebeef5;
}

.section :deep(.el-descriptions__cell) {
  border: 1px solid #ebeef5;
  padding: 16px 20px;
}

.section :deep(.el-descriptions__label) {
  background: #f5f7fa;
  font-weight: 600;
  color: #606266;
  font-size: 14px;
}

.section :deep(.el-descriptions__content) {
  color: #303133;
  font-weight: 500;
  font-size: 14px;
}

/* 表格样式 */
.el-table {
  border-radius: 8px;
  border: 1px solid #ebeef5;
}

.el-table :deep(.el-table__header) {
  background: #f5f7fa;
}

.el-table :deep(.el-table__header th) {
  background: transparent;
  color: #606266;
  font-weight: 600;
  border: none;
  padding: 16px 12px;
  font-size: 14px;
}

.el-table :deep(.el-table__body tr:hover) {
  background: #f5f7fa;
}

.el-table :deep(.el-table__body td) {
  border: 1px solid #ebeef5;
  padding: 16px 12px;
  font-weight: 500;
  color: #303133;
  font-size: 14px;
}

/* 操作按钮样式 - 导出按钮放在左上角 */
.op-row{ 
  display:flex; 
  justify-content:flex-start; 
  margin-bottom: 20px;
  gap: 12px;
}

.op-row .el-button {
  font-weight: 500;
  padding: 10px 20px;
  border-radius: 6px;
  font-size: 14px;
}

/* 底部按钮样式 */
.section-card {
  background: white;
  border: 1px solid #ebeef5;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0,0,0,0.1);
  margin-top: 20px;
}

.section-card :deep(.el-card__body) {
  padding: 24px;
}

.op-bottom{ 
  display:flex; 
  justify-content:center; 
  gap:16px; 
}

.op-bottom .el-button {
  font-weight: 500;
  padding: 12px 24px;
  border-radius: 6px;
  font-size: 14px;
}

/* 标签样式 */
.el-tag {
  border-radius: 4px;
  font-weight: 500;
  padding: 4px 12px;
  font-size: 12px;
}

/* 链接样式 */
.el-link {
  font-weight: 500;
}

/* 颜色色块样式 */
.color-swatch{ 
  width:24px; 
  height:24px; 
  border-radius:4px; 
  border:1px solid #ddd;
}

/* 占位符样式 */
.placeholder{ 
  color:#999; 
  padding:40px 0; 
  text-align: center;
  font-size: 14px;
  background: #f5f7fa;
  border-radius: 6px;
  margin: 20px 0;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .detail-wrap {
    padding: 16px;
    gap: 16px;
  }
  
  .card-header .meta {
    gap: 20px;
    flex-direction: column;
  }
  
  .btn-bar {
    flex-direction: column;
    align-items: stretch;
  }
  
  .op-bottom {
    flex-direction: column;
    align-items: stretch;
  }
  
  .detail-tabs :deep(.el-tabs__content) {
    padding: 16px;
  }
  
  .section {
    padding: 16px;
  }
}
</style>

